package com.aggregate.pay.transfar.support;

import java.net.SocketTimeoutException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import com.aggregate.pay.transfar.bean.AbstractData;
import com.aggregate.pay.transfar.bean.Result;
import com.aggregate.pay.transfar.enums.ResultStatus;
import com.aggregate.pay.transfar.support.utils.JSON;

/**
 * 接口API操作类抽象类
 * @author Moyq5
 * @date 2017年9月29日
 * @param <D>
 * @param <R>
 */
public abstract class AbstractClient<D extends AbstractData, R> implements Client<D, R> {
		
	private Merch merch;
	
	public AbstractClient(Merch merch) {
		this.merch = merch;
	}
	
	@Override
	public Result<R> execute(D data) {
		Result<R> resResult = null;
		try {
			data.setAppId(merch.appId());
			data.setTimestamp(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
			
			HttpClient client = Factory.getHttpClient();
			Map<String, String> params = getReqParams(data);
			String resBody = client.post(Factory.getConfig().getServerPath(), params);
			return JSON.toObject(resBody, resultClass());
			
		} catch (SocketTimeoutException e) {
			resResult = new Result<R>();
			resResult.setStatus(ResultStatus.EXCEPTION);
			resResult.setCode("C9999");
			resResult.setMsg("请求超时");
		} catch (Exception e) {
			log.error("接口调用失败", e);
			resResult = new Result<R>();
			resResult.setStatus(ResultStatus.EXCEPTION);
			resResult.setCode("C9999");
			resResult.setMsg("本地错误：" + e.getMessage());
		}
		return resResult;
	}
	
	private Map<String, String> getReqParams(D data) throws Exception {
		return Tool.sign(data, merch.key());
	}
	
	protected abstract Class<? extends Result<R>> resultClass();
	
}
